package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.Message;
import com.example.demo.entity.DTO.unreadDTO;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author yolo
 * @since 2025-03-28
 */
@Mapper
public interface MessageMapper extends BaseMapper<Message> {

    @Select("select * from message where receiver_id = #{receiverId} and is_read = 0")
    List<Message> findByReceiverIdAndIsReadFalse(Integer receiverId);

    void getUnReadMessageListByUsername(String username);

    @MapKey("key")
    @Select("select message.sender_id as senderId, count(*) as count from message where receiver_id = #{receiveId} and is_read = 0 group by sender_id")
    List<unreadDTO> getUserIdListByReceiveIdAndIsReadFalse(Integer receiveId);


    @Select("WITH lastSenderId AS (SELECT sender_id FROM message WHERE receiver_id = #{receiveId} AND is_read = 0 ORDER BY create_at DESC LIMIT 1) \n" +
            "SELECT" +
            "  id," +
            "  content," +
            "  create_at," +
            "  sender_id," +
            "  receiver_id\n" +
            "FROM" +
            "  message\n" +
            "WHERE\n" +
            "  (sender_id = #{receiveId} AND receiver_id IN (SELECT sender_id FROM lastSenderId))\n" +
            "  OR (sender_id IN (SELECT sender_id FROM lastSenderId) AND receiver_id = #{receiveId})\n" +
            "ORDER BY\n" +
            "  create_at\n" +
            "LIMIT 20")
    List<Message> getLastMessageSessionByReceiveIdAndReadFalse(Integer receiveId);

    @Select("select id, content, create_at, sender_id, receiver_id " +
            "from message " +
            "where (sender_id = #{senderId} and receiver_id = #{receiveId}) " +
            "or (sender_id = #{receiveId} and receiver_id = #{senderId}) " +
            "order by create_at DESC " +
            "limit 20 offset #{offset}")
    List<Message> getSessionMessageByReceiveIdAndSenderId(Integer receiveId, Integer senderId, Integer offset);

    @Select("select distinct message.sender_id from message where receiver_id = #{userId} " +
            "union " +
            "select distinct message.receiver_id from message where sender_id = #{userId} and receiver_id != ''")
    List<Integer> getChatList(Integer userId);

    @Select("select count(*) as count, sender_id from message where receiver_id = #{userId} and is_read = 0 and sender_id group by sender_id")
    List<unreadDTO> getUnReadCountListByReceiveId(Integer userId);

    @Select("select count(*) from message where receiver_id = #{userId} and is_read = 0")
    Integer getUnreadCountByUserId(Integer userId);
}
